package net.wwang.config;

import net.wwang.utils.UpdateClassUtil;
import org.apache.log4j.*;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;

/**
 * @Description: 修改class字节码文件
 * @Author: WangWei
 * @CreateTime: 2020-07-02 10:48
 */
public class ClassUpdateFrame extends JFrame implements ActionListener {
    private static Logger logger = Logger.getLogger(FileUpdateFrame.class);
    JFrame mainFrame;
    JPanel panel;
    //Label
    JLabel infile = new JLabel("文件路径");
    JLabel outlogpath_label = new JLabel("过程日志路径");
    JLabel searchStr = new JLabel("位置");
    JLabel replaceStr = new JLabel("替换");
    JTextArea outtext_textarea = new JTextArea();
    //文本域
    JTextField intextField = new JTextField(30);
    JTextField searchField = new JTextField(50);
    JTextField replaceField = new JTextField(50);
    JTextField outlogpath_textfield = new JTextField(20);
    //滚动条
    JScrollPane jScrollPane;
    //创建按钮
    JButton backBtn = new JButton("返回");
    JButton nextBtn = new JButton("继续");
    JButton infilepath_button = new JButton("...");
    JButton outlogpath_button = new JButton("...");
    JButton start_button = new JButton("开始修改");

    public void showFrame() {
        //mainFrame = new JFrame("WwangTools V1.0");
        mainFrame = new JFrame("修改字节码文件");
        //窗口宽度高度大小
        mainFrame.setSize(575, 600);
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //固定窗口
        mainFrame.setResizable(false);
        Toolkit kit = Toolkit.getDefaultToolkit(); // 定义工具包
        Dimension screenSize = kit.getScreenSize(); // 获取屏幕的尺寸
        int screenWidth = screenSize.width / 2; // 获取屏幕的宽
        int screenHeight = screenSize.height / 2; // 获取屏幕的高
        int height = mainFrame.getHeight(); //获取窗口高度
        int width = mainFrame.getWidth(); //获取窗口宽度
        mainFrame.setLocation(screenWidth - width / 2, screenHeight - height / 2);//将窗口设置到屏幕的中部
        //窗体居中，c是Component类的父窗口
        //mainframe.setLocationRelativeTo(c);
        String str = "/net/wwang/static/wwang.jpg";
        Image myimage = kit.getImage(mainFrame.getClass().getResource(str)); //由tool获取图像
        mainFrame.setIconImage(myimage);
        inifPanel();//初始化面板
        mainFrame.add(panel);
        mainFrame.setVisible(true);
    }

    /* 创建面板，这个类似于 HTML 的 div 标签
     * 我们可以创建多个面板并在 JFrame 中指定位置
     * 面板中我们可以添加文本字段，按钮及其他组件。
     */
    private void inifPanel() {
        this.panel = new JPanel();
        panel.setLayout(null);
        //this.panel = new JPanel(new GridLayout(3,2)); //创建3行3列的容器
        /* 这个方法定义了组件的位置。
         * setBounds(x, y, width, height)
         * x 和 y 指定左上角的新位置，由 width 和 height 指定新的大小。
         */
        infile.setBounds(10, 20, 120, 25);
        intextField.setBounds(120, 20, 400, 25);
        infilepath_button.setBounds(520, 20, 30, 25);
        this.panel.add(infile);
        this.panel.add(intextField);
        this.panel.add(infilepath_button);

        outlogpath_label.setBounds(10, 80, 120, 25);
        outlogpath_textfield.setBounds(120, 80, 400, 25);
        outlogpath_button.setBounds(520, 80, 30, 25);
        this.panel.add(outlogpath_label);
        this.panel.add(outlogpath_textfield);
        this.panel.add(outlogpath_button);

        start_button.setBounds(370, 150, 120, 25);
        this.panel.add(start_button);
        outtext_textarea.setEditable(false);
        outtext_textarea.setFont(new Font("Microsoft YaHei", Font.BOLD, 16));
        jScrollPane = new JScrollPane(outtext_textarea);
        jScrollPane.setBounds(10, 185, 550, 330);
        this.panel.add(jScrollPane);
        searchStr.setBounds(10, 150, 50, 25);
        searchField.setBounds(70, 150, 100, 25);
        this.panel.add(searchStr);
        this.panel.add(searchField);

        replaceStr.setBounds(180, 150, 50, 25);
        replaceField.setBounds(240, 150, 100, 25);
        this.panel.add(replaceStr);
        this.panel.add(replaceField);
        //增加动作监听

        backBtn.setBounds(400,540,70,25);
        nextBtn.setBounds(490,540,70,25);
        this.panel.add(backBtn);
        this.panel.add(nextBtn);
        infilepath_button.addActionListener(this);
        outlogpath_button.addActionListener(this);
        start_button.addActionListener(this);
        nextBtn.addActionListener(this);
        backBtn.addActionListener(this);
    }

    /**
     * 单击动作触发方法
     *
     * @param event
     */
    @Override
    public void actionPerformed(ActionEvent event) {
        // TODO Auto-generated method stub
        System.out.println(event.getActionCommand());
        if (event.getSource() == start_button) {
            //确认对话框弹出
            int result = JOptionPane.showConfirmDialog(null, "是否开始修改?", "确认", 0);//YES_NO_OPTION
            if (result == 1) {//是：0，否：1，取消：2
                return;
            }
            System.out.println(intextField.getText());
            if (intextField.getText().equals("")) {
                JOptionPane.showMessageDialog(null, "路径不能为空", "提示", 2);//弹出提示对话框，warning
                return;
            } else {
                String infilepath = intextField.getText();
                int seachIndex =Integer.parseInt( searchField.getText());
                String replaceText = replaceField.getText();
                String outlogpath = outlogpath_textfield.getText();
                //设置log4j日志输出格式以及路径
                Layout layout = new PatternLayout("%-d{yyyy-MM-dd HH:mm:ss}  [ %C{1}--%M:%L行 ] - [ %p ]  %m%n");
                Appender appender = null;
                try {
                    appender = new FileAppender(layout, outlogpath + "\\log.log");
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                logger.addAppender(appender);
                System.out.println(outlogpath + "\\log.log");
                logger.debug("修改开始\n");
                outtext_textarea.append("修改开始!\n");

                try {
                    UpdateClassUtil.updateClass(infilepath,replaceText,seachIndex);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                logger.debug("修改结束\n");
                outtext_textarea.append("修改结束!\n");
                outtext_textarea.append("此工具来自-王为 CodeWwang ,作者QQ:592245268\n");
                outtext_textarea.append("此工具的版权归-王为个人所有，如需商用请联系作者\n");
                result = JOptionPane.showConfirmDialog(null, "是否打开日志文件?", "确认", 0);//YES_NO_OPTION
                if (result == 0) {//是：0，否：1，取消：2
                    try {
                        @SuppressWarnings("Unused")
                        Process process = Runtime.getRuntime().exec("cmd.exe  /c notepad " + outlogpath + "\\log.log");//调用cmd方法使用记事本打开文件
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }
        } else {
            //判断三个选择按钮并对应操作
            if (event.getSource() == infilepath_button) {
                //选择文件夹
                File file = openChoseWindow(JFileChooser.DIRECTORIES_ONLY);
                //选择路径
                //File file = openChoseWindow(JFileChooser.FILES_ONLY);
                if (file == null)
                    return;
                intextField.setText(file.getAbsolutePath());
            } else if (event.getSource() == outlogpath_button) {
                File file = openChoseWindow(JFileChooser.DIRECTORIES_ONLY);
                if (file == null)
                    return;
                outlogpath_textfield.setText(file.getAbsolutePath() + "\\log");
            }else if(event.getSource()==backBtn){
                mainFrame.setVisible(false);
                new WwangUtilsHomeFrame().showFrame();
                dispose();
            }
        }
    }

    /**
     * 打开选择文件窗口并返回文件
     *
     * @param type
     * @return
     */
    public File openChoseWindow(int type) {
        JFileChooser jfc = new JFileChooser();
        jfc.setFileSelectionMode(type);//选择的文件类型(文件夹or文件)
        jfc.showDialog(new JLabel(), "选择");
        File file = jfc.getSelectedFile();
        return file;
    }

    /**
     * 关闭方法
     *
     * @param arg0
     */
    public void windowClosed(WindowEvent arg0) {
        System.exit(0);
    }

    public void windowClosing(WindowEvent arg0) {
        System.exit(0);
    }

}
